package com.example.utils;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author ChenXiaoBin
 * on 2019-07-09
 */
@Slf4j
public class ProxyUtils {
    private static final String VALIDATE_URL = "http://117.50.75.80:8080/V1.0/post";

    public static String validateHttp(String ip, int port, String param) {
        PrintWriter out = null;
        StringBuilder sb = new StringBuilder();
        boolean available = false;
        HttpURLConnection connection = null;
        try {
            //需要访问的地址、创建链接
            URL url = new URL(VALIDATE_URL);
            //代理对象
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
            connection = (HttpURLConnection) url.openConnection(proxy);
            connection.setRequestProperty("accept", "");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-type","application/json");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
            connection.setConnectTimeout(2 * 1000);
            connection.setReadTimeout(3 * 1000);
            connection.setInstanceFollowRedirects(false);
//            "Proxy-Authorization"= "Basic Base64.encode(user:password)";
            String headerKey = "Proxy-Authorization";
            String headerValue = "Basic " + Base64.encode("test"+":"+ "test");
            connection.setRequestProperty(headerKey, headerValue);
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String s = null;

            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            if (connection.getResponseCode() == 200) {
                available = true;
            }
            log.info("validateHttp ==> ip:{} port:{} info:{}", ip, port, connection.getResponseMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            available = false;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return sb.toString();
    }

    //使用ProxySelector
    public static void httpProxy() throws IOException {
        ProxySelector.setDefault(new ProxySelector() {

            @Override
            public List<Proxy> select(URI uri) {
                List<Proxy> list = new ArrayList<Proxy>();
                list.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
                        "10.10.8.84", 8080)));
                return list;
            }

            @Override
            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                System.out.println("连接代理失败！");
            }

        });
        // 需要访问的地址
        String urlStr = "http://www.baidu.com";
        // 创建连接
        URL url = new URL(urlStr);
        URLConnection conn = url.openConnection();
        // 输出访问结果
        try {
            Scanner scan = new Scanner(conn.getInputStream());
            StringBuilder builder = new StringBuilder();
            while (scan.hasNextLine()) {
                builder.append(scan.nextLine()).append(urlStr);
            }
            System.out.println(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
